import AppGradient from "@/components/AppGradient";
import { router, useLocalSearchParams } from "expo-router";
import React, { useContext, useEffect, useState } from "react";
import { ImageBackground, Pressable, Text, View } from "react-native";
import { AntDesign } from "@expo/vector-icons";
import { Audio } from "expo-av";
import CustomButton from "@/components/CustomButton";

import MEDITATION_IMAGES from "@/constants/meditation-images";
import { TimerContext } from "@/context/TimerContext";
import { MEDITATION_DATA, AUDIO_FILES } from "@/constants/MeditationData";

const Page = () => {
    const { id } = useLocalSearchParams();
//从 TimerContext 上下文中获取 duration 和 setDuration，用于管理倒计时状态。
    const { duration: secondsRemaining, setDuration } =
        useContext(TimerContext);

    const [isMeditating, setMeditating] = useState(false);//是否处于冥想状态
    const [audioSound, setSound] = useState<Audio.Sound>();//存储音频对象
    const [isPlayingAudio, setPlayingAudio] = useState(false);//储音频是否正在播放

    useEffect(() => {
        let timerId: NodeJS.Timeout;

        // 当我们达到 0 时提前退出
        if (secondsRemaining === 0) {
            if (isPlayingAudio) audioSound?.pauseAsync();
            setMeditating(false);
            setPlayingAudio(false);
            return;
        }

        if (isMeditating) {
            // 保存间隔 ID 以便在组件卸载时清除它
            timerId = setTimeout(() => {
                setDuration(secondsRemaining - 1);
            }, 1000);
        }

        //如果组件已卸载或剩余时间发生变化，则清除超时
        return () => {
            clearTimeout(timerId);
        };
    }, [secondsRemaining, isMeditating]);

    // 卸载时重置倒计时并卸载音频
    useEffect(() => {
        return () => {
            setDuration(10);
            audioSound?.unloadAsync();
            //在组件卸载时，卸载音频对象。
            // unloadAsync 是 expo-av 提供的用于卸载音频的方法。
        };
    }, [audioSound]);
    //初始化音频
    const initializeSound = async () => {
        const audioFileName = MEDITATION_DATA[Number(id) - 1].audio;//对应的音频文件名

        const { sound } = await Audio.Sound.createAsync(
            AUDIO_FILES[audioFileName]
        );//创建音频对象并加载音频文件
        setSound(sound);
        return sound;
    };
    //异步函数，用于 切换音频的播放、暂停状态。
    const togglePlayPause = async () => {
        //如果音频对象已存在，直接使用；否则 初始化音频对象
        const sound = audioSound ? audioSound : await initializeSound();
        //获取音频对象的状态。
        const status = await sound?.getStatusAsync();

        //更新 isPlayingAudio 状态，存储音频播放状态
        if (status?.isLoaded && !isPlayingAudio) {
            await sound?.playAsync();//播放
            setPlayingAudio(true);//更新 isPlayingAudio 状态，存储音频播放状态。
        } else {
            await sound?.pauseAsync();//暂停
            setPlayingAudio(false);//更新 isPlayingAudio 状态，存储音频播放状态。
        }
    };
    //切换冥想状态
    async function toggleMeditationSessionStatus() {

        if (secondsRemaining === 0) setDuration(10);//倒计时结束，重置倒计时

        setMeditating(!isMeditating);//切换 是否冥想 状态

        await togglePlayPause();//切换音频的播放和暂停状态
    }
    //调整冥想时长
    const handleAdjustDuration = () => {
        if (isMeditating) toggleMeditationSessionStatus();//如果处于冥想状态，先停止冥想。

        router.push("/(modal)/adjust-meditation-duration");
    };

    // 格式化时间
    const formattedTimeMinutes = String(
        Math.floor(secondsRemaining / 60)
    ).padStart(2, "0");//将秒数转换为分钟，并格式化为两位数。
    const formattedTimeSeconds = String(secondsRemaining % 60).padStart(2, "0");//将剩余秒数格式化为两位数。

    return (
        <View className="flex-1">
            <ImageBackground
                source={MEDITATION_IMAGES[Number(id) - 1]}
                resizeMode="cover"
                className="flex-1"
            >
                <AppGradient colors={["transparent", "rgba(0,0,0,0.8)"]}>
                    
                    <Pressable
                        onPress={() => router.back()}
                        className="absolute top-16 left-6 z-10"
                    >
                        <AntDesign name="leftcircleo" size={50} color="white" />
                    </Pressable>

                    <View className="flex-1 justify-center">
                        <View className="mx-auto bg-neutral-200 rounded-full w-44 h-44 justify-center items-center">
                            <Text className="text-4xl text-blue-800 font-rmono">
                                {formattedTimeMinutes}.{formattedTimeSeconds}
                            </Text>
                        </View>
                    </View>

                    <View className="mb-5">
                        <CustomButton
                            title="Adjust duration"
                            onPress={handleAdjustDuration}
                        />
                        <CustomButton
                            title={isMeditating ? "Stop" : "Start Meditation"}
                            onPress={toggleMeditationSessionStatus}
                            containerStyles="mt-4"
                        />
                    </View>
                </AppGradient>
            </ImageBackground>
        </View>
    );
};

export default Page;
